package com.lyj.hw_student.system.controller;

import com.lyj.hw_student.system.entity.SysUser;
import com.lyj.hw_student.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/sysUser")
public class SysUserController {

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 保存用户信息
     * @param sysUser
     * @return
     */
    @PostMapping("/save")
    public String save(@RequestBody SysUser sysUser) {
        sysUserService.save(sysUser);
        return "success";
    }

    /**
     * 获取所有用户信息
     * @return
     */
    @GetMapping("/getAllUsers")
    public List<SysUser> getAllUsers() {
        return sysUserService.list();
    }

    /**
     * 登录
     * @param userName
     * @param password
     * @return
     */
    @GetMapping("/login")
    public String login(@RequestParam("userName") String userName,
                        @RequestParam("password") String password) {
        SysUser user = sysUserService.findByName(userName);
        if (user == null) {
            return "用户名不存在";
        }
        if (!user.getPassword().equals(password)) {
            return "密码错误";
        }
        return "success";
    }

    /**
     * 测试接口
     * @return
     */
    @RequestMapping("/test")
    public String test() {
        return "test";
    }

    /**
     * 添加用户
     * @param sysUser
     * @return
     */
    @PostMapping("/adduser")
    public String addUser(@RequestBody SysUser sysUser) {
        sysUserService.save(sysUser);
        return "success";
    }

    /**
     * 删除用户
     * @param userId
     * @return
     */
    @DeleteMapping("/delUser/{userId}")
    public String delUser(@PathVariable Integer userId) {
        sysUserService.removeById(userId);
        return "success";
    }

    /**
     * 修改用户信息
     * @param sysUser
     * @return
     */
    @PutMapping("/updateUser")
    public String updateUser(@RequestBody SysUser sysUser) {
        sysUserService.updateById(sysUser);
        return "success";
    }

    /**
     * 查询用户信息
     * @param userId
     * @return
     */
    // 修改后的查询功能
    @GetMapping("/getUser/{userId}")
    public SysUser getUser(@PathVariable Integer userId) {
        return sysUserService.getById(userId);
    }

    /**
     * 搜索用户信息
     * @param userName
     * @return
     */
    @GetMapping("/search")
    public List<SysUser> searchUsers(@RequestParam("userName") String userName) {
        return sysUserService.lambdaQuery()
                .like(SysUser::getUserName, userName)
                .list();
    }
}